package br.com.passeionaweb.appengine.tabelafipe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.passeionaweb.appengine.tabelafipe.data.DataProvider;
import br.com.passeionaweb.appengine.tabelafipe.data.Make;
import br.com.passeionaweb.appengine.tabelafipe.data.Model;
import br.com.passeionaweb.appengine.tabelafipe.data.PMF;
import br.com.passeionaweb.appengine.tabelafipe.data.Version;
import br.com.passeionaweb.appengine.tabelafipe.data.Year;
import br.com.passeionaweb.appengine.tabelafipe.data.YearVersion;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class UpdateMakesServlet extends HttpServlet {

	private static final PersistenceManager pm = PMF.get().getPersistenceManager();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
			IOException {
		long start = Calendar.getInstance().getTimeInMillis();
		boolean result = updateMakes();
		if(result){
			Queue q = QueueFactory.getDefaultQueue();
			q.purge();
			TaskOptions o = TaskOptions.Builder.withUrl("/updatemodels");
			o.countdownMillis(2000);
			o.method(Method.GET);
			q.add(o);
			o = TaskOptions.Builder.withUrl("/updateversions");
			o.countdownMillis(12000);
			o.method(Method.GET);
			q.add(o);
			o = TaskOptions.Builder.withUrl("/updateyears");
			o.countdownMillis(80000);
			o.method(Method.GET);
			q.add(o);
			o = TaskOptions.Builder.withUrl("/updateyearversion");
			o.countdownMillis(90000);
			o.method(Method.GET);
			q.add(o);
		}
		long end = Calendar.getInstance().getTimeInMillis();
		resp.getWriter().write("{result:"+result+",time:"+((end - start) / 1000)+"}");
	}

	private boolean updateMakes() {
		boolean result = true;
		try {
			JSONArray jsonMakes = new JSONArray(DataProvider.getMakesJSON());
			List<Make> makes = new ArrayList<Make>();
			for (int i = 0; i < jsonMakes.length(); ++i) {
				JSONObject jsonmake = jsonMakes.getJSONObject(i);
				String makeName = jsonmake.getString(Make.KEY_MAKE);
				if (!Make.exists(makeName)) {
					makes.add(new Make(makeName));
				}
				logPercentage(i, jsonMakes.length());
			}
			if (makes.size() != 0) {
				pm.makePersistentAll(makes);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			result = false;
		} catch (IOException e) {
			e.printStackTrace();
			result = false;
		}
		return result;
	}
	
	
	private void logPercentage(int done, int size) {
		float percentage = Float.valueOf(done) / Float.valueOf(size) * 100;
		System.out.println("Updating MAKES: " + percentage + "%");
	}
	/*
	 * private boolean clearMakes() { try { Query query =
	 * pm.newQuery(Make.class); List<Make> makes = (List<Make>) query.execute();
	 * pm.deletePersistentAll(makes); return true; }catch(Exception e) {
	 * e.printStackTrace(); return false; }
	 * 
	 * }
	 */

}
